//
//  HomeView.m
//  eticket
//
//  Created by AnhQuocNguyen on 4/10/13.
//  Copyright (c) 2013 SoinMedia. All rights reserved.
//

#import "HomeView.h"

@implementation HomeView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
      
    }
    return self;
}
- (void)dealloc {
    [_btnPre release];
    [_btnNext release];
    [_parentSliderView release];
    SAFE_RELEASE_OBJECT(_tblViewEvent);
    SAFE_RELEASE_OBJECT(_arrListEvent);
    SAFE_RELEASE_VIEW(refeshHeaderTableView);
    SAFE_RELEASE_VIEW(mHud);
    [super dealloc];
}



#pragma mark - Setup UI
- (void)setupUIforHomeView{
    
    ////////////////////////////////////////////////////////
    //Setup Slider
    _parentSliderView.backgroundColor = [UIColor clearColor];
    _parentSliderView.clipsToBounds = YES;
    _parentSliderView.layer.borderWidth = .2;
    _parentSliderView.layer.borderColor = [[UIColor colorWithRed:237/255 green:237/255 blue:237/255 alpha:.2] CGColor];
    _btnNext.exclusiveTouch = YES;
    _btnPre.exclusiveTouch = YES;

    _indexSlider = 0;
    _isClick = NO;
    _countTimeout = 0;
    mLoading = YES;
    
    [self initHUD:@"Loading...."];
    [mHud showWhileExecuting:@selector(waitting) onTarget:self withObject:nil animated:NO];

    ////////////////////////////////////////////////////////
    //Setup tableView
    _arrListEvent = [[NSMutableArray alloc] init];
    
    //Get slider truoc roi get events
    [self getSlider];
}
- (void)enableButtonSlider:(BOOL)enable{
    _btnNext.userInteractionEnabled = enable;
    _btnPre.userInteractionEnabled = enable;
    _tblViewEvent.userInteractionEnabled = enable;
}
- (void)refreshToServer{
    mLoading = YES;
    [self initHUD:@"Loading...."];
    [mHud showWhileExecuting:@selector(waitting) onTarget:self withObject:nil animated:NO];
    
    [self getSlider];
}

#pragma mark - buttonSlider_Clicked
- (IBAction)buttonSlider_Clicked:(id)sender{
    
    [self stopTimer];
    
    UIButton *button = (UIButton *)sender;
    button.userInteractionEnabled = NO;
    
    if (button == _btnNext) {
        __block UIImageView *imgView = (UIImageView *)[_parentSliderView.subviews objectAtIndex:_indexSlider];
        
        [UIView animateWithDuration:0.7 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            imgView.alpha = 0.04;
        } completion:^(BOOL finished) {
            //////////////////////////////////////////////////////////////////////////////////////////
            if (_indexSlider < [_parentSliderView.subviews count]) {
                _indexSlider++;
                NSLog(@"Click Next --- Current Index: %d", _indexSlider);
                if (_indexSlider == [_parentSliderView.subviews count]) {
                    _indexSlider = 0;
                }
            }
            //////////////////////////////////////////////////////////////////////////////////////////
            __block UIImageView *imgViewNext = (UIImageView *)[_parentSliderView.subviews objectAtIndex:_indexSlider];
            [UIView animateWithDuration:0.7 animations:^{
                imgView.alpha = 0;
                imgViewNext.alpha = 1;
                button.userInteractionEnabled = YES;
                [self startTimer];
            }];
        }];
        
    }
    else{
        __block UIImageView *imgView = (UIImageView *)[_parentSliderView.subviews objectAtIndex:_indexSlider];
        
        [UIView animateWithDuration:1 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            imgView.alpha = 0.04;
        } completion:^(BOOL finished) {
            //////////////////////////////////////////////////////////////////////////////////////////
            if (_indexSlider >= 0) {
                _indexSlider--;
                NSLog(@"Click Pre --- Current Index: %d", _indexSlider);
                if (_indexSlider < 0 ) {
                    _indexSlider = [_parentSliderView.subviews count] - 1;
                }
            }
            //////////////////////////////////////////////////////////////////////////////////////////
            __block UIImageView *imgViewNext = (UIImageView *)[_parentSliderView.subviews objectAtIndex:_indexSlider];
            [UIView animateWithDuration:1 animations:^{
                imgView.alpha = 0;
                imgViewNext.alpha = 1;
                button.userInteractionEnabled = YES;
                [self startTimer];
            }];
        }];
    }
}

#pragma mark - UIAlertView Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == ALERT_LISTEVENT_HOME) {
        mLoading = YES;
        [self initHUD:@"Loading...."];
        [mHud showWhileExecuting:@selector(waitting) onTarget:self withObject:nil animated:NO];
            [self getEvents];
    }
    
    if (alertView.tag == ALERT_SLIDER_HOME) {
            [self refreshToServer];
    }
}

/////////////////////////////////////////////////////////////////////////////////

#pragma mark - Get Slider
- (void)getSlider{
    dispatch_async(kBgQueue, ^{
        NSString *urlString =[NSString stringWithFormat:@"%@%@%@", URL_island_API, sliders_API, TOKEN__island];
        NSURL *url = [NSURL URLWithString:urlString];
        ASIFormDataRequest *requestServer = [ASIFormDataRequest requestWithURL:url];
        [requestServer setTimeOutSeconds:20];
        [requestServer setCompletionBlock:^{
            NSError *error = nil;
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:[requestServer responseData] options:kNilOptions error:&error];
            /////////////////////////////////////////////////////////////////////
            //Set error server
            if (error) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[error description] delegate:self cancelButtonTitle:nil otherButtonTitles:@"Refesh", nil];
                alert.tag = ALERT_SLIDER_HOME;
                [alert show];
                SAFE_RELEASE_OBJECT(alert);
                return;
            }
            
            /////////////////////////////////////////////////////////////////////
            //Set error json
            NSDictionary *jsonError = [jsonDic objectForKey:@"error"];
            if ([[jsonError objectForKey:@"code"] intValue] != 200) {
                NSArray *messageArray = [jsonError objectForKey:@"message"];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[messageArray objectAtIndex:0] delegate:self cancelButtonTitle:nil otherButtonTitles:@"Refesh", nil];
                alert.tag = ALERT_SLIDER_HOME;
                [alert show];
                SAFE_RELEASE_OBJECT(alert);
                return;
            }
            
            
            //Create Image Slider
            NSArray *arrSlider = [[jsonDic objectForKey:@"data"] objectForKey:@"sliders"];
            for (NSInteger i = 0; i < [arrSlider count]; i++) {
                
                NSDictionary *sliderDictionary = [arrSlider objectAtIndex:i];
                NSString *urlString = [NSString stringWithFormat:@"%@%@", URL_island, [sliderDictionary objectForKey:@"thumbnail"]];
                NSURL *url = [NSURL URLWithString:urlString];
                
                UIImageView *imgViewSlider = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, _parentSliderView.bounds.size.width, _parentSliderView.bounds.size.height)];
                imgViewSlider.tag = IMAGE_SLIDER_TAG + i;
                imgViewSlider.clipsToBounds = YES;
                imgViewSlider.contentMode = UIViewContentModeScaleAspectFill;
                [imgViewSlider setImageWithURL:url placeholderImage:[UIImage imageNamed:@"Loading.png"]];
                if (i!=0) {
                    imgViewSlider.alpha = 0;
                }
                [_parentSliderView addSubview:imgViewSlider];
                SAFE_RELEASE_OBJECT(imgViewSlider);
            }
            
            //Run Timer
            [self startTimer];
            
            //Sau khi get thanh cong slider thi get event
            [self getEvents];
            
        }];
        
        [requestServer setFailedBlock:^{
            mLoading = NO;
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Load slider faild !!!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Refesh", nil];
            alert.tag = ALERT_SLIDER_HOME;
            [alert show];
            SAFE_RELEASE_OBJECT(alert);
        }];
        
        
        [requestServer startSynchronous];
    });
}


#pragma mark - Get Events
- (void)getEvents{
    dispatch_async(kBgQueue, ^{
        //Server
        NSString *urlString =[NSString stringWithFormat:@"%@%@%@", URL_island_API, events_API, TOKEN__island];
        NSURL *url = [NSURL URLWithString:urlString];
        ASIFormDataRequest *requestServer = [ASIFormDataRequest requestWithURL:url];
        [requestServer setTimeOutSeconds:20];
        [requestServer setCompletionBlock:^{
            
            NSError *error = nil;
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:[requestServer responseData] options:kNilOptions error:&error];
            
            /////////////////////////////////////////////////////////////////////
            //Set error server
            if (error) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[error description] delegate:self cancelButtonTitle:nil otherButtonTitles:@"Refesh", nil];
                alert.tag = ALERT_LISTEVENT_HOME;
                [alert show];
                SAFE_RELEASE_OBJECT(alert);
                return;
            }
            
            
            /////////////////////////////////////////////////////////////////////
            //Set error json
            NSDictionary *jsonError = [jsonDic objectForKey:@"error"];
            if ([[jsonError objectForKey:@"code"] intValue] != 200) {
                NSArray *messageArray = [jsonError objectForKey:@"message"];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[messageArray objectAtIndex:0] delegate:self cancelButtonTitle:nil otherButtonTitles:@"Refesh", nil];
                alert.tag = ALERT_LISTEVENT_HOME;
                [alert show];
                SAFE_RELEASE_OBJECT(alert);
                return;
            }
            
            ////////////////////////////////////////////////////////////////////
            //Set data
            NSLog(@"Get data event from server !!!!");
            NSDictionary *dataEvents = [jsonDic objectForKey:@"data"];
            NSArray *listEvent = [dataEvents objectForKey:@"events"];
            if ([_arrListEvent count] > 0) {
                [_arrListEvent removeAllObjects];
            }
            for (NSInteger i = 0; i < [listEvent count]; i++) {
                NSDictionary *dicEvent = [listEvent objectAtIndex:i];
                EventTicket *event = [[EventTicket alloc] init];
                event.idEvent = [dicEvent objectForKey:@"id"];
                event.titleEvent = [dicEvent objectForKey:@"title"];
                event.slug = [dicEvent objectForKey:@"slug"];
                event.startTimeEvent = [dicEvent objectForKey:@"start_time"];
                event.endTimeEvent = [dicEvent objectForKey:@"end_time"];
                event.thumbnailEvent = [dicEvent objectForKey:@"thumbnail"];
                event.description = [dicEvent objectForKey:@"description"];
                
                [_arrListEvent addObject:event];
                SAFE_RELEASE_OBJECT(event);
            }
            
            //Set tableview & pull to refesh
            [self setupTableViewListEvent];
            [self setupPullToRefesh];
            mLoading = NO;
            
            //Post delegate
            if ([_HomeViewDelegate respondsToSelector:@selector(homeViewDidFinishDowloadData:)]) {
                [_HomeViewDelegate homeViewDidFinishDowloadData:self];
            }
        }];
        
        
        [requestServer setFailedBlock:^{
            mLoading = NO;
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Load events faild !!!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Refesh", nil];
            alert.tag = ALERT_LISTEVENT_HOME;
            [alert show];
            SAFE_RELEASE_OBJECT(alert);
        }];
        
        [requestServer startSynchronous];
    });
}


/////////////////////////////////////////////////////////////////////////////////
#pragma mark - Run Timer
- (void)startTimer{
    NSLog(@"Start Timer");
    _isClick = NO;
    _timerSlider = [NSTimer scheduledTimerWithTimeInterval:8 target:self selector:@selector(runSlider) userInfo:nil repeats:YES];
}
- (void)stopTimer{
        NSLog(@"Stop Timer");
        [_timerSlider invalidate];
        _timerSlider = nil;
}
- (void)runSlider{
    
    __block UIImageView *imgView = (UIImageView *)[_parentSliderView.subviews objectAtIndex:_indexSlider];
    [UIView animateWithDuration:4 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        imgView.alpha = 0.04;
    } completion:^(BOOL finished) {
        //////////////////////////////////////////////////////////////////////////////////////////
        if (_indexSlider < [_parentSliderView.subviews count]) {
            _indexSlider++;
            if (_indexSlider == [_parentSliderView.subviews count]) {
                _indexSlider = 0;
            }
        }
        
        //////////////////////////////////////////////////////////////////////////////////////////
        __block UIImageView *imgViewNext = (UIImageView *)[_parentSliderView.subviews objectAtIndex:_indexSlider];
        [UIView animateWithDuration:4 animations:^{
            imgView.alpha = 0;
            imgViewNext.alpha = 1;
            _isClick = YES;
        }];
    }];
}





/////////////////////////////////////////////////////////////////////////////////
#pragma mark - setupTableViewListEvent
- (void)setupTableViewListEvent{
    if (!_tblViewEvent) {
        _tblViewEvent = [[UITableView alloc] initWithFrame:CGRectMake(16, 165, 288, [Utilities isDeviceFourInches] ? 290 : 190)];
        _tblViewEvent.backgroundColor = [UIColor clearColor];
        _tblViewEvent.delegate = self;
        _tblViewEvent.dataSource = self;
        _tblViewEvent.exclusiveTouch = YES;
        _tblViewEvent.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self addSubview:_tblViewEvent];
    }
    else{
        [_tblViewEvent reloadData];
    }
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_arrListEvent count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"ListEventViewCell";
    ListEventViewCell *cell = (ListEventViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ListEventViewCell" owner:self options:nil];
        for (id curr in nib) {
            if ([curr isKindOfClass:[ListEventViewCell class]]) {
                cell = (ListEventViewCell *)curr;
                cell.exclusiveTouch = YES;
                cell.listEventViewCellDelegate = self;
                [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
                break;
            }
        }
    }
   
    cell.eventIndex = indexPath.row;
    EventTicket *event = [_arrListEvent objectAtIndex:indexPath.row];

    NSArray *arrStartDate = [event.startTimeEvent componentsSeparatedByString:@" "];
    cell.lbDate.text = [arrStartDate objectAtIndex:0];
    
    cell.txtDescription.text = [Utilities stringByStrippingHTML:event.description];
    
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@",URL_island, event.thumbnailEvent];
    NSURL *url = [NSURL URLWithString:urlString];
    [cell setupForCell];
    [cell.imgViewAvatar setImageWithURL:url placeholderImage:[UIImage imageNamed:@"loading.png"]];
    return cell;
}





/////////////////////////////////////////////////////////////////////////////////
//Tu eventDetail quay ve
#pragma mark - listEventViewCell Delegate
- (void)listEventViewCellDidSelectedEvent:(ListEventViewCell *)listEventViewCell{
    if (!_eventDetailView) {
        POOL_START
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"EventDetailView" owner:self options:nil];
        _eventDetailView = (EventDetailView *)[nib objectAtIndex:0];
        _eventDetailView.frame = CGRectMake(330, [Utilities isDeviceFourInches] ? 38 : 43, 320, [UIScreen mainScreen].bounds.size.height - 43);
        [self.superview addSubview:_eventDetailView];
        POOL_END
    }
    
     EventTicket *eventTicket = (EventTicket *)[_arrListEvent objectAtIndex:listEventViewCell.eventIndex];
     _eventDetailView.eventSlug = eventTicket.slug;
     [_eventDetailView setupEventDetailView];
     [_eventDetailView getDataFromServer];
     _eventDetailView.eventDetailViewDelegate = self;
    
    [UIView animateWithDuration:0.3 animations:^{
        
        CGRect frameTempCategory = self.frame;
        frameTempCategory.origin.x = - 320;
        self.frame = frameTempCategory;
        
        CGRect frametemp = _eventDetailView.frame;
        frametemp.origin.x = 0;
        _eventDetailView.frame = frametemp;
        
    } completion:^(BOOL finished) {
        self.hidden = YES;
        if([_HomeViewDelegate respondsToSelector:@selector(homeViewDidSlectedGetTicket:)]){
            [_HomeViewDelegate homeViewDidSlectedGetTicket:self];
        }
    }];
}


/////////////////////////////////////////////////////////////////////////////////
#pragma mark - EventDetailView Delegate
- (void)eventDetailViewWithback:(EventDetailView *)evenDetailView{
    
    self.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        
        CGRect frameTempCategory = self.frame;
        frameTempCategory.origin.x = 0;
        self.frame = frameTempCategory;
        
        CGRect frametemp = evenDetailView.frame;
        frametemp.origin.x = 330;
        evenDetailView.frame = frametemp;
        
    } completion:^(BOOL finished) {
        if([_HomeViewDelegate respondsToSelector:@selector(homeViewBackFromEventDetailView:)]){
            [_HomeViewDelegate homeViewBackFromEventDetailView:self];
        }
        _eventDetailView.eventDetailViewDelegate = nil;
    }];
}




/////////////////////////////////////////////////////////////////////////////////
//scroll to top
#pragma mark - scrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	[refeshHeaderTableView egoRefreshScrollViewDidScroll:scrollView];
    
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	[refeshHeaderTableView egoRefreshScrollViewDidEndDragging:scrollView];
    
}


/////////////////////////////////////////////////////////////////////////////////
//Pull to refesh
#pragma mark - setupPullToRefesh
- (void)setupPullToRefesh{
    if (refeshHeaderTableView == nil) {
        refeshHeaderTableView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - _tblViewEvent.bounds.size.height, self.frame.size.width, _tblViewEvent.bounds.size.height)];
        refeshHeaderTableView.delegate = self;
        [_tblViewEvent addSubview:refeshHeaderTableView];
        _tblViewEvent.backgroundColor = [UIColor clearColor];
        [refeshHeaderTableView setWhiteTextColor];
    }
    else{
        [self doneLoadingTableViewData];
    }
}

#pragma mark EGORefreshTableHeader Delegate
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
    
    [self reloadTableViewDataSource];
	
    // send request to server
    [NSObject cancelPreviousPerformRequestsWithTarget:self
                                             selector:@selector(refreshTime)
                                               object:nil];
    
    addingDuration = 0;
    [self getEvents];
}
-(void)refreshTime{
    addingDuration ++;
    
    [self performSelector:@selector(refreshTime) withObject:nil afterDelay:60.0];
    
}
- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	NSLog(@"Data Source Last Updated");
	return [NSDate date];
	
}
- (void)reloadTableViewDataSource{
	NSLog(@"ReloadTable view source");
	_reloading = YES;
	
}
- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	return _reloading; // should return if data source model is reloading
	
}
- (void)doneLoadingTableViewData{
	//  model should call this when its done loading
    NSLog(@"Done Loading Table View Data");
	_reloading = NO;
	[refeshHeaderTableView egoRefreshScrollViewDataSourceDidFinishedLoading:_tblViewEvent];
	
}





/////////////////////////////////////////////////////////////////////////////////
#pragma mark - MBProgressHUD
-(void)initHUD:(NSString *)alert {
    if (mHud) {
        [mHud removeFromSuperview];
        SAFE_RELEASE_OBJECT(mHud);
    }
    mHud = [[MBProgressHUD alloc] initWithView:self];
    //    mHud.delegate = self;
    mHud.labelText = alert;
    mHud.dimBackground = YES;
    [self addSubview:mHud];
    
}
-(void)waitting{
    while (mLoading) {
        usleep(5000);
    }
}

@end
